package com.romotc.qqrobot.webqq.qqInterfaceCatching;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import com.romotc.scache.RequestSpy;
import com.romotc.scache.WebConnection;

public class ProxyHtml extends QQUrlBodyModifyCatching {

	/**
	 * 使用修改后的proxy.html
	 */
	@Override
	public String modifyResponseBody(String origResPonseBody, RequestSpy rqSpy) {
		// TODO Auto-generated method stub
		File proxyhtml = new File("./web/proxy.html");
		try {
			if(proxyhtml.exists()) {
				FileInputStream fis = new FileInputStream(proxyhtml);
				InputStreamReader reader = new InputStreamReader(fis, rqSpy.resCharSet);
				StringBuffer buf = new StringBuffer();
				char[] b = new char[512];
				int len = 0;
				while((len = reader.read(b)) != -1) {
					buf.append(b, 0, len);
//					System.out.println(new String(b,0,len));
				}
				
//				Map<String, String> h1 = new HashMap<String, String>();
//				h1.put("transfer-encoding", "");
//				rqSpy.headers = modifyResHeaders(rqSpy.headers,h1);
				rqSpy.chunked = false;
				
				return buf.toString();
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return super.modifyResponseBody(origResPonseBody, rqSpy);
	}

	
	public static void main(String args[]) {
		File proxyhtml = new File("./web/proxy.html");
		System.out.println(proxyhtml.exists());
	}


	@Override
	public boolean hackRequest(RequestSpy requestSpy) {
		//make_headers(200, "message/http", null, null, -1, 0, 0, null);
		byte[] b;
		try {
			File proxyhtml = new File("./web/proxy.html");
			FileInputStream fis = new FileInputStream(proxyhtml);
			DataInputStream dis = new DataInputStream(fis);
			int len = (int)proxyhtml.length();
			requestSpy.make_headers(200, null, null, null, len, new Date()
				.getTime(), System.currentTimeMillis() + 1000 * 60, null);
			
			requestSpy.send_headers();
			WebConnection wc = new WebConnection(dis);
			requestSpy.transfer_object(wc, null, null);
			return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.hackRequest(requestSpy);
	}
}
